#include "ApplicationScene.hpp"
#include "Application.hpp"
#include "../video/Screen.hpp"
#include "../core/Game.hpp"

namespace yep
{
ApplicationScene::ApplicationScene()
{
}

ApplicationScene::~ApplicationScene()
{
}

void ApplicationScene::setup( Game &game )
{
    selected = 0;
    vector<Application*> &applicationMap = Application::getApplications();

    for( auto it = applicationMap.begin(); it != applicationMap.end(); ++it ) {
        applicationList.push_back( (*it)->getName() );
    }
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
}

void ApplicationScene::cleanup( Game &game )
{
    applicationList.clear();
    SDL_EnableKeyRepeat(0,0);
}

void ApplicationScene::logic( Game &game )
{
    SDL_Event event;

    while( SDL_PollEvent( &event ) ) {
        switch( event.type ) {
        case SDL_QUIT:
            game.exit();
            break;
        case SDL_KEYDOWN:
            switch(event.key.keysym.sym)
            {
            case SDLK_ESCAPE:
                game.exit();
                break;
            case SDLK_UP:
                if(selected >0)
                    --selected;
                break;
            case SDLK_DOWN:
                if(selected < applicationList.size()-1)
                    ++selected;
                break;
            case SDLK_SPACE:
            case SDLK_RETURN:
            case SDLK_KP_ENTER:
                if(applicationList.size() > 0)
                {
                    string selectedString = applicationList[selected];
                    Application &selectedApplication = *Application::applications[selected];
                    game.setCurrentScene(selectedApplication.getFirstScene());
                    Screen::getInstance().setCaption(selectedApplication.getName());
                }
                break;
            default:
                break;
            }
            break;
        }
    }
}

void ApplicationScene::draw( Game &game )
{
    unsigned y = 0;
    Screen &screen = Screen::getInstance();
    const string welcome("Choose a Application");

    screen.fillRectangle(Vector2(0, 0), Vector2(screen.getWidth()-1,8), Color::DARK_GRAY);
    screen.drawText(Vector2((screen.getWidth()-welcome.size()*8)/2, 0), Color::LIGHT_YELLOW, welcome);
    screen.drawRectangle(Vector2(0, selected*8+8), Vector2(screen.getWidth(),8), Color::YELLOW);

    unsigned i=0;
    for (auto it = applicationList.begin(); it != applicationList.end(); ++it)
    {
        screen.drawText(Vector2(0,y+=8), i++==selected?Color::WHITE:Color::LIGHT_GRAY, *it);
        if(y >= screen.getHeight())
            break;
    }
}

}
